package gz.copydatabase.Utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Endeavor on 2016/9/25 0025.
 * Detail：带时分秒
 */

public class DateUtils {
    public enum Flag {
        SS,
        MM
    }
    public static Date getCurrentDatetime(){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MILLISECOND,-calendar.get(Calendar.MILLISECOND));
        calendar.add(Calendar.SECOND,-calendar.get(Calendar.SECOND));
        return calendar.getTime();
    }
    public static Date getCurrentDatetime(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MILLISECOND,-calendar.get(Calendar.MILLISECOND));
        calendar.add(Calendar.SECOND,-calendar.get(Calendar.SECOND));
        return calendar.getTime();
    }
    public static Date getNowDatetime(Date nowDate){
        nowDate.setHours(0);
        nowDate.setMinutes(0);
        getCurrentDatetime(nowDate);
        return getCurrentDatetime(nowDate);
    }
    public static Date getBeforeYear(Date date) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(date);
        ca.add(Calendar.MONTH,-1);
        return  ca.getTime();
    }
    public static String date2String(Date date, Flag flag) {
        if(flag== Flag.MM)
            return DateUtils.date2String(date,"yyyy-MM-dd HH:mm");
        if(flag== Flag.SS)
            return DateUtils.date2String(date,"yyyy-MM-dd HH:mm:ss");
        return  null;
    }
    public static Date string2Date(String date, Flag flag) {

        if(flag== Flag.MM)
            return DateUtils.string2Date(date,"yyyy-MM-dd HH:mm");
        if(flag== Flag.SS)
            return DateUtils.string2Date(date,"yyyy-MM-dd HH:mm:ss");
        return  null;
    }
    public static String date2String(Date date, String dateFormat){
        if(date==null)
            return "";
        return  new SimpleDateFormat(dateFormat).format(date);
    }
    public static Date string2Date(String date, String dateFormat) {
        try {
            return   new SimpleDateFormat(dateFormat).parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String change(String date) {
        // +8:00 /> String
        try {
            String time = date.split("M")[0].replace("T", " ").substring(0, 11);
            return time;
        } catch (Exception e) {
            e.toString();
            return date;
        }
    }
}
